// index.js
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var login = require('../../utils/login.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    goodsDetail: {},
    swiperCurrent: 0,
    hasMoreSelect: false,
    selectSize: "",
    selectSizePrice: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 0,
    buyNumMin: 0,
    buyNumMax: 0,
    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    favorite: false,
    CurrentPid: 0,
    ReviewListLength: 0,
    animationData: "",
    showModalStatus: false,
    skuTitles: [],
    attrvalue: "",
    img: "",
    TotalCount: 0,
    showAppoint: false,
    typeList: [],
    disId: 0,
    agentId: 0,
    animationData2: "",
    showModalStatus2: false,
    productCode: "",
    pathGoods: ""
  },
  tokefu:function(){
    wx.switchTab({
      url: '/pages/kefu/index',
    })
  },
  //获取商品二维码
  getWxaCode: function () {
    var that = this
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        path: that.data.pathGoods,
        storeappid: app.globalData.storeAppId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.setData({
              productCode: 'http://static.711688.net.cn/upload/user/' + res.data.Data
            })
          }
        }
      },
    })
  },
  preview: function () {
    var that = this
    wx.previewImage({
      current: that.data.productCode, // 当前显示图片的http链接
      urls: [that.data.productCode] // 需要预览的图片http链接列表
    })
  },
  // 弹出层
  showModal2: function (e) {
    this.getWxaCode()
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    this.setData({
      animationData2: animation.export(),
      showModalStatus2: true
    })
    setTimeout(function () {
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal2: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    this.setData({
      animationData2: animation.export(),
    })
    setTimeout(function () {
      this.setData({
        animationData2: animation.export(),
        showModalStatus2: false
      })
    }.bind(this), 200)
  },
  GetCouponTypeList: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/store/GetSendingCouponTypeList',
      data: {
        storeid: app.globalData.storeId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var couPonList = res.data.Data
          for (var i = 0; i < couPonList.length; i++) {
            couPonList[i].UseStartTime = couPonList[i].UseStartTime.slice(0, 10)
            couPonList[i].UseEndTime = couPonList[i].UseEndTime.slice(0, 10)
          }
          that.setData({
            typeList: res.data.Data
          })
        }
      }
    })
  },
  //规格选择颜色变化
  selectAttr: function (e) {
    var that = this;
    var namearr = e.currentTarget.dataset.namearr
    var attrid = e.currentTarget.dataset.attrid
    var skulist = that.data.skuTitles
    var kid = 0//颜色变化初始值
    for (var i = 0; i < skulist.length; i++) {//一级数组
      var nameArr = skulist[i].nameArr
      for (var j = 0; j < nameArr.length; j++) {//二级数组
        if (nameArr[j].IsInput == 1) {
          var nameAttrValue = nameArr[j].InputValue
        } else {
          var nameAttrValue = nameArr[j].attrvalue
        }
        if (nameAttrValue == namearr) {
          if (nameArr[j].kid == 0) {
            nameArr[j].kid = 1
          }
          else {
            nameArr[j].kid = 0
          }
        }
        else if (nameAttrValue != namearr && attrid == nameArr[j].AttrId) {
          nameArr[j].kid = 0
        }
        else if (attrid != nameArr[j].AttrId) {
          if (nameArr[j].kid != 1) {
            nameArr[j].kid = 3
            that.selectionPid(skulist, namearr, attrid)
          }
        }
      }
    }
    that.setData({
      skuTitles: skulist
    })
    var pidArr = []
    for (var p = 0; p < skulist.length; p++) {//选中对应kid筛选pid
      var nameArry = skulist[p].nameArr
      var arry = skulist[p].arr
      for (var h = 0; h < nameArry.length; h++) {
        if (nameArry[h].kid == 1) {
          if (nameArry[h].IsInput == 0) {
            var nameAttrValue = nameArry[h].attrvalue
          } else {
            var nameAttrValue = nameArry[h].InputValue
          }
          for (var m = 0; m < arry.length; m++) {
            if (arry[m].IsInput == 0) {
              var arrAttrValue = arry[m].AttrValue
            } else {
              var arrAttrValue = arry[m].InputValue
            }
            if (nameAttrValue == arrAttrValue) {
              pidArr.push(arry[m].Pid)
            }
          }
        }
      }
    }
    var nary = pidArr.sort();
    that.arrRepeat(nary, skulist.length)//一共几组sku skulist.length
  },
  //查找数组重复次数的组合pid
  arrRepeat: function (arr, skuCount) {
    var that = this
    var arrStr = JSON.stringify(arr), str;
    for (var i = 0; i < arr.length; i++) {
      if ((arrStr.match(new RegExp(arr[i], "g")).length) == skuCount) {//出现重复的次数等于sku组的出现次数
        that.setData({
          CurrentPid: arr[i]//最终的组合pid
        })
        that.getGoodsInfo()
      }
    }
  },
  //返回选中的pid
  selectionPid: function (skulist, text, attrid) {
    var that = this;
    for (var i = 0; i < skulist.length; i++) {
      if (attrid == skulist[i].AttrId) {
        var arr = skulist[i].arr
        for (var j = 0; j < arr.length; j++) {
          if (arr[j].IsInput == 0) {
            var arrAttrValue = arr[j].AttrValue
          } else {
            var arrAttrValue = arr[j].InputValue
          }
          if (text == arrAttrValue) {
            var Pid = arr[j].Pid
            that.otherPid(skulist, Pid, attrid)
          }
        }
      }
    }
  },
  //判断另一组可选择的规格值
  otherPid: function (skulist, pid, attrid) {
    var that = this;
    var valueArr = []
    for (var i = 0; i < skulist.length; i++) {
      if (attrid != skulist[i].AttrId) {
        var arr = skulist[i].arr
        var nameArr = skulist[i].nameArr
        for (var j = 0; j < arr.length; j++) {
          if (pid == arr[j].Pid) {
            if (arr[j].IsInput == 0) {
              var AttrValue = arr[j].AttrValue
            } else {
              var AttrValue = arr[j].InputValue
            }
            that.check2(valueArr, AttrValue)
            if (!that.check2(valueArr, AttrValue)) {
              valueArr.push(AttrValue)
              for (var f = 0; f < valueArr.length; f++) {
                for (var k = 0; k < nameArr.length; k++) {
                  if (nameArr[k].IsInput == 0) {
                    var nameArrValue = nameArr[k].attrvalue
                  } else {
                    var nameArrValue = nameArr[k].InputValue
                  }
                  if (valueArr[f] == nameArrValue && nameArr[k].kid != 1) {
                    nameArr[k].kid = 0
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  //数组去重
  check2: function (arr, text) {
    var state = false;  //默认不存在
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        if (text == arr[i]) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },
  //接口取值
  onProductSKU: function (pid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/Product',
      data: {
        pid: pid
      },
      success: function (res) {
        console.log(res)
        if (res.data.Code == 0) {
          var skuList = res.data.Data.ProductSKUList
          var skuTitle = res.data.Data.CurrProductSkuList
          for (var k = 0; k < skuTitle.length; k++) {//初始化二维数组
            skuTitle[k].arr = []
            skuTitle[k].nameArr = []
          }
          that.ProductSKU(skuTitle, skuList);
        } else {
          wx.showModal({
            title: '获取失败',
            content: '',
            showCancel: false
          })
        }
      }
    })
  },
  //重新push新数组
  ProductSKU: function (skuTitle, skuList) {
    var that = this;
    var skuTitles = skuTitle
    var skuList = skuList
    for (var i = 0; i < skuTitles.length; i++) {
      for (var j = 0; j < skuList.length; j++) {
        if (skuTitles[i].AttrId == skuList[j].AttrId) {
          var f = {}
          f.AttrId = skuList[j].AttrId
          f.AttrName = skuList[j].AttrName
          f.AttrValue = skuList[j].AttrValue
          f.Pid = skuList[j].Pid
          f.RecordId = skuList[j].RecordId
          f.IsInput = skuList[j].IsInput
          f.InputValue = skuList[j].InputValue
          f.sid = 0
          f.ShowImg = app.globalData.image800_800host + skuList[j].ShowImg
          skuTitles[i].arr.push(f)
          if (skuList[j].IsInput == 1) {//手动输入
            var skuValue = skuList[j].InputValue
          } else {
            var skuValue = skuList[j].AttrValue
          }
          if (!that.check(skuTitles[i].nameArr, skuValue)) {
            skuTitles[i].nameArr.push({
              attrvalue: skuList[j].AttrValue, kid: 0, AttrId: skuList[j].AttrId, IsInput: skuList[j].IsInput, InputValue: skuList[j].InputValue
            })
          }
        }
      }
    }
    that.setData({
      skuTitles: skuTitles
    })
  },
  //数组去重
  check: function (arr, text) {
    var state = false;  //默认不存在
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        if (text == arr[i].attrvalue || text == arr[i].InputValue) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },
  // 底部弹出层
  showModal: function () {
    // 显示遮罩层
    this.onProductSKU(this.data.CurrentPid)
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  //事件处理函数
  swiperchange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    this.GetCouponTypeList()
    if (e.agentId) {
      wx.setStorageSync("agentid", e.agentId);

    }
    if (e.disId) {
      wx.setStorageSync("disid", e.disId);
    }
    this.setData({
      CurrentPid: e.id,
      showAppoint: app.globalData.showAppoint
    });
  },
  // subscribe预约
  subscribe: function (e) {
    wx.navigateTo({
      url: '/pages/yuyue/index?pid=' + this.data.CurrentPid + "&name=" + this.data.goodsDetail.ProductInfo.Name,
    });
  },
  selectGoods: function (e) {
    wx.navigateTo({
      url: '/pages/pingjia-list/index?pid=' + this.data.CurrentPid
    })
  },
  numJianTap: function () {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function () {
    if (this.data.buyNumber < this.data.buyNumMax) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  addShopCar: function (e) {
    if (e != 0) {
      var add = e.currentTarget.dataset.add
    }
    var that = this;
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '暂时缺货哦~',
        showCancel: false
      })
      return;
    }
    wx.request({
      url: app.globalData.host + '/api/cart/AddProduct',
      data: {
        uid: app.globalData.userInfo.Uid,
        pid: that.data.CurrentPid,
        buyCount: that.data.buyNumber
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            shopNum: res.data.Data
          });
          if (add != 1) {
            that.goShopCar();
          } else {
            wx.showToast({
              title: '加入购物车成功',
              icon: 'success',
              duration: 2000
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  goShopCar: function () {
    wx.navigateTo({
      url: "/pages/shop-cart/index"
    });
  },
  tobuy: function (e) {
    var isSkuProduct = e.currentTarget.dataset.sku
    if (isSkuProduct > 0) {
      this.showModal()
    } else {
      if (this.data.buyNumber < 1) {
        wx.showModal({
          title: '提示',
          content: '暂时缺货哦~',
          showCancel: false
        })
        return;
      }
      this.addShopCar(0);
    }
  },
  favorite: function (e) {
    var that = this;
    var pid = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.host + '/api/user/ProductFavorite',
      data: {
        pid: pid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var oldF = that.data.favorite;
          if (oldF) {
            wx.showModal({
              title: '取消收藏成功',
              content: '',
              showCancel: false
            })
          } else {
            wx.showModal({
              title: '收藏成功',
              content: '',
              showCancel: false
            })
          }
          that.setData({ favorite: !oldF })
        }
      }
    })
  },
  initPage: function () {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    // 获取购物车数据
    wx.request({
      url: app.globalData.host + '/api/cart/index',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({ shopNum: res.data.Data.TotalCount })
        }

      }
    })

    wx.request({
      url: app.globalData.host + '/api/user/CheckProductFavorite',
      data: {
        pid: that.data.CurrentPid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        var f = res.data.Data;
        that.setData({ favorite: f })
      }
    })
    that.getGoodsInfo();
  },
  //获取商品信息
  getGoodsInfo: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/store/Product',
      data: {
        pid: that.data.CurrentPid
      },
      success: function (res) {
        var p = res.data.Data;
        if (!p.ProductInfo || p.ProductInfo.State != 0) {
          wx.showModal({
            title: '商品已下架',
            content: '',
            showCancel: false
          })
          return;
        }
        if (p.ProductInfo.ShowImg) {
          p.ProductInfo.ShowImg = app.globalData.image800_800host + p.ProductInfo.ShowImg;
        }
        for (var i = 0; i < p.ProductImageList.length; i++) {
          p.ProductImageList[i].ShowImg = app.globalData.image800_800host + p.ProductImageList[i].ShowImg;
        }
        if (p.ExtGiftList) {
          for (var i = 0; i < p.ExtGiftList.length; i++) {
            p.ExtGiftList[i].ShowImg = app.globalData.image190_190host + p.ExtGiftList[i].ShowImg;
          }
        }

        var selectSizeTemp = "";
        var pnames = "";
        if (p.CurrProductSkuList.length > 0) {
          for (var i = 0; i < p.CurrProductSkuList.length; i++) {
            pnames += p.CurrProductSkuList[i].AttrName + ":";
            var value = p.CurrProductSkuList[i].AttrValue;
            if (p.CurrProductSkuList[i].IsInput) {
              value = p.CurrProductSkuList[i].InputValue;
            }
            selectSizeTemp = selectSizeTemp + " " + value;
            pnames += value + " "
          }
          that.setData({
            hasMoreSelect: true,
            selectSize: that.data.selectSize + selectSizeTemp,
            selectSizePrice: p.ProductInfo.ShopPrice,
            propertyChildNames: pnames
          });
        }
        that.setData({
          goodsDetail: p,
          selectSizePrice: p.ProductInfo.ShopPrice,
          buyNumMax: p.StockNumber,
          buyNumber: (p.StockNumber > 0) ? 1 : 0
        });
        WxParse.wxParse('article', 'html', p.ProductInfo.Description, that, 5);
        wx.hideLoading();
      }
    })
  },
  //获取评价列表
  pingjiaList: function (pid) {
    var that = this;
    var postDatalist = {
      uid: app.globalData.userInfo.Uid,
      page: 1
    };
    wx.request({
      url: app.globalData.host + '/api/store/productreviewlist?pid=' + pid + '&page=1',
      success: (res) => {
        if (res.data.Code == 0) {
          var ReviewListTwo = [];
          that.setData({
            ReviewListLength: res.data.Data.ProductReviewList.length,
            TotalCount: res.data.Data.PageModel.TotalCount
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      that.initPage();
      that.pingjiaList(that.data.CurrentPid);
      that.GetSharePagePath()
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    wx.stopPullDownRefresh();
  },


  //分享
  onShareAppMessage: function () {
    return {
      title: this.data.goodsDetail.ProductInfo.Name,
      path: this.data.pathGoods,
      success: function (res) {
        // 转发
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  //获取分销商信息
  GetSharePagePath: function () {
    var that = this;
    var disId = wx.getStorageSync('disid')
    var agentId = wx.getStorageSync('agentid')
    if (!disId) {
      disId = 0
    }
    if (!agentId) {
      agentId = 0
    }
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributorAndCreate',
      data: {
        userId: app.globalData.userInfo.Uid,
        storeId: app.globalData.storeId,
        disId: disId,
        agentId: agentId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var path = '';
          var fromuid = app.globalData.userInfo.Uid;
          if (res.data.Data.IsAgent == 0) {
            path = '/pages/index/index?fromuid=' + fromuid + "&disId=" + res.data.Data.Id + "&agentId=" + res.data.Data.AgentDId
          } else {
            path = '/pages/index/index?fromuid=' + fromuid + "&disId=" + res.data.Data.Id + "&agentId=" + res.data.Data.AgentDId
          }
          that.setData({
            pathGoods: path
          })
        }
      }
    })
  },
})